# -*- coding: utf-8 -*-
from odoo import models,fields
from odoo.exceptions import UserError,ValidationError
from odoo.addons import decimal_precision as dp
import logging

_logger = logging.getLogger(__name__)

class ImportWizard(models.TransientModel):
    _name = 'import.wizard'
    _inherit = 'import.excel.wizard'
    _description = '导入向导'

    HEARDER_ROW = 1  # 标题的行号
    COLUMN_MAP = {
        '产品件号': 'default_code',
        '产品描述': 'name',
        '单价': 'list_price',
        '起订量': 'min_qty',
        '折扣':'rate',
        '单位': 'uom_name',
        '供应商': 'supplier',
        '货期':'delay',
        '备注': 'remark',
        '料号':'default_code2'
    }
    def _validate_data(self, rownum, format_data):
        default_code = format_data.get('default_code', False)
        if not default_code:
            self.row_error_info.append('没用件号')

    def _format_data(self, field_name, value):
        if isinstance(value, str):
            value = value.strip()
        elif isinstance(value,float) and (field_name=="default_code" or field_name=="default_code2"): 
            value=str(value).split(".")[0] #将xlrd返回的cell.value（比如9938.0转换成9938）转换成字符串
        return value

    #导入前的处理接口（覆盖源文件import_excel_wizard.py中的方法）
    def _before_process_row_data(self, book, sheet):
       pass
    # 导入操作 （覆盖源文件import_excel_wizard.py中的方法）
    def _process_row_data(self, rownum, data):
        categ_id=self.env.context.get('category_id')
        import_purchase=self.env.context.get('import_purchase')
        description = data.get('remark','').strip()
        list_price = data.get('list_price',0)
        rate = data.get('rate',0.0)
        name = data.get('name','').strip()
        default_code = str(data.get('default_code','')).strip()
        default_code2 = str(data.get('default_code2','')).strip()
        datestart=self.env['product.category'].browse(categ_id).datestart
        dateend=self.env['product.category'].browse(categ_id).dateend

        prdt = self.env['product.product'].search(
            [('default_code', '=', default_code), ('categ_id', '=', categ_id),('type','=','product')])
        if prdt:  # 更新产品信息
            if name:
                prdt.name = name
            if not import_purchase:  # 在导入销售价格时（不是只导入采购价），赋值
                prdt.list_price = list_price
            if description:
                prdt.description = description
            if default_code2:
                prdt.default_code2 = default_code2
            # prdt.description = fields.Date.to_string(fields.Date.today())
        else:
            # 创建导入的产品
            val = {
                'name': name,
                'default_code': default_code,
                'sale_ok': True,
                'purchase_ok': True,
                'type': 'product',
                'route_ids': [(4, self.env.ref('purchase_stock.route_warehouse0_buy').id)],
                'uom_id': self.env.ref('uom.product_uom_unit').id,
                'uom_po_id': self.env.ref('uom.product_uom_unit').id,
                'categ_id': categ_id,
                'description': description,
                'default_code2':default_code2
            }
            if not import_purchase:  # 在导入销售价格时（不是只导入采购价），修改销售的list_price
                val['list_price'] = list_price
            prdt = self.env['product.product'].create(val)
        # 更新 purchase 相关信息
        supplier = data.get('supplier','').strip()
        if import_purchase:  # 只导入采购价
            price = list_price
        else:
            price = list_price * rate  # 导入销售价并更新采购价
        min_qty = data.get('min_qty',1)
        delay = data.get('delay',1)
        partner = self.env['res.partner'].search([('name', '=', supplier)])
        if partner:
            partnerid = partner.id
            if price == 0:
                return
            # supplierinfo = prdt.seller_ids.filtered(lambda x: x.name.id == partnerid)
            # if supplierinfo:
            #     for s in supplierinfo:
            #         if not s.min_qty:
            #             s.min_qty = min_qty
            #         s.price = price
            #         if not s.delay:
            #             s.delay = delay
            #         s.date_revised=fields.Date.today()
            # else:
            #     val = {'name': partnerid, 'min_qty': min_qty, 'price': price, 'delay': delay,
            #     'date_revised':fields.Date.today(),'datestart':datestart,'dateend':dateend}
            #     prdt.seller_ids = [(0, 0, val)]
            val = {'name': partnerid, 'min_qty': min_qty, 'price': price, 'delay': delay,
            'date_revised':fields.Date.today(),'date_start':datestart,'date_end':dateend}
            if not prdt.seller_ids:
                prdt.seller_ids = [(0,0,val)]
            sinfo=sorted(prdt.seller_ids,key=lambda x:x.id,reverse=True)[0]
            if round(sinfo.price,0) != round(price,0):
                prdt.seller_ids = [(0, 0, val)]
                # 更新cost
                sinfo=sorted(prdt.seller_ids,key=lambda x:x.id,reverse=True)[0]
                self.env['product.category'].update_cost(sinfo)


    # 导入后的操作 （覆盖源文件import_excel_wizard.py中的方法）
    def _after_process_row_data(self, book, sheet):
        pass
